<style rel="stylesheet/scss" lang="scss" scoped>
	.info {
		display: flex;
		height: 100%;
		flex-direction: column;
		.content-head {
			width: 100%;
			height: auto;
			border: 1px solid #f0f0f0;
			.head-tit {
				width: 100%;
				height: 30px;
				display: flex;
				line-height: 40px;
				.text-q {
					color: #409EFF;
				}
			}
			.m-t-30 {
				margin-top: 30px;
			}
		}
		.table-box {
			padding: 10px;
			height: auto;
			margin-top: 20px;
			overflow: auto;
			border: 1px solid #F0F0F0;
		}
		.exl-box {
			text-decoration: none;
			color: #fff;
			font-size: 12px;
			background-color: #409EFF;
			border-color: #409EFF;
			line-height: 1;
			white-space: nowrap;
			cursor: pointer;
			padding: 7px 15px;
			border-radius: 3px;
		}
		.sl-box {
			padding-top: 15px;
		}
		.fil-box {
			position: fixed;
			top: 0px !important;
			right: 0px !important;
			left: 0px !important;
			bottom: 0px !important;
			z-index: 100;
			background-color: rgba(0, 0, 0, 0.5);
		}
		.close-box {
			width: 100%;
			height: 40px;
			color: #1973bf;
			cursor: pointer;
			line-height: 40px;
			text-align: center;
		}
		.dowdBox {
			left: 50%;
			top: 50%;
			width: 300px;
			border-radius: 10px;
			position: fixed;
			display: flex;
			padding: 10px;
			margin-left: -150px;
			margin-top: -80px;
			flex-direction: column;
			background: #fff;
			border: 1px solid #E5E5E5;
		}
		.dowdBox>a {
			width: 100%;
			height: 40px;
			text-decoration: none;
			line-height: 40px;
			background: #409EFF;
			text-align: center;
			color: #fff;
			border-radius: 5px;
			display: inline-block;
		}
		.dowdBox-title{
			width: 100%;
			height: 80px;
			line-height: 80px;
			text-align: center;
		}
	}
</style>
<template>
	<div class="info" v-loading.fullscreen.lock="fullscreenLoading">
		<div class="content-head">
			<div class="head-tit m-t-10 m-b-10">
				<span class="m-l-10 text-14" >商品编码:</span>
				<el-input maxLength="20" style="width: 180px;" class="m-l-10 " placeholder="商品编码" v-model="goodsModelNumber" size="mini"></el-input>
				<span class="m-l-10 m-r-10 text-14" style="margin-right: 10px;">时间:</span>
				<el-date-picker 
					v-model="beginTime" 
					type="datetime" 
					placeholder="选择开始时间" 
					align="right" 
					style="width: 180px;" 
					:picker-options="pickerOptions1" 
					size="mini" >
				</el-date-picker>
				<span class="m-l-10 m-r-10 text-14" style="width: 15px;">至:</span>
				<!--<el-input placeholder="店名关键字" maxLength="20" style="width: 150px;" class="m-l-10"></el-input>-->
				<el-date-picker 
					v-model="endTime" 
					type="datetime" 
					placeholder="选择结束时间" 
					align="right"
					style="width: 180px;" 
					:picker-options="pickerOptions1" 
					size="mini" >
				</el-date-picker>
				<span class="m-l-10 text-q text-14" @click="getOneWeekDate(1)" style="cursor: pointer;">最近7天</span>
				<span class="m-l-10 text-q text-14" @click="getOneWeekDate(2)" style="cursor: pointer;">最近30天</span>
			</div>
			<div class="head-tit m-t-10 " style="display: flex;align-items: center;">
				<span class="m-l-10 m-r-10 text-14" style="margin-right: 14px;">品牌名:</span>
				<el-input 
					maxLength="20" 
					style="width: 180px;" 
					class="m-l-10" 
					placeholder="品牌关键字" 
					v-model="brandName" 
					size="mini">
				</el-input>
				<span class="m-l-10 m-r-10 text-14">品类:</span>
				<template>
					<el-select v-model="firstCatId" placeholder="请选择" class="m-r-10" size="mini" style="width: 180px;">
						<el-option v-for="item in firstCatList" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</template>
				<template>
					<el-select v-model="secCatId" placeholder="请选择" size="mini" style="width: 180px;">
						<el-option v-for="item in secCatList" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</template>
				<span class="m-l-10 m-r-10 text-14">商品状态:</span>
				<template >
					<div >
						<el-select v-model="onlineStatus" placeholder="请选择" class="m-r-10" size="mini" @change="selectOnlineFn" style="width: 180px;">
							<el-option v-for="item in onlineList" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
						<el-button type="primary" size="mini" @click="screenFn(1)">筛选</el-button>
						<el-button type="primary" size="mini" @click="screenFn(2)">重置</el-button>
						
					</div>
				</template>
			</div>
			
			<el-row class="m-t-10 m-l-10">
				
				<!--<el-button type="primary">导出excel</el-button>-->
			</el-row>
		</div>
		<div class="sl-box">
			<el-row class="m-l-10">
				<el-button type="success" size="mini" @click="newProductFn">新建</el-button>
				<el-button type="success" size="mini" @click="batchExportFn">批量导入</el-button>
				<a href="http://118.31.19.251:9001/goods/import/template/" download="product.xlsx" class="exl-box" >导入模板</a>
				<el-button type="primary" size="mini" @click="uploadImg">上传图片</el-button>
				<el-button type="danger" size="mini" @click="closeImgAll">清空图片</el-button>
				<el-button type="primary" size="mini" @click="updateStatusAllFn(true)">批量上架</el-button>
				<el-button type="primary" size="mini" @click="updateStatusAllFn(false)">批量下架</el-button>
				<el-button type="danger" size="mini" @click="deleteAllClick">批量删除</el-button>
				<a :href="handle_goods_url" download="product.xlsx" class="exl-box" >导出excel</a>
			</el-row>
		</div>
			  
		<div class="table-box">

			<template>
				<el-table ref="multipleTable" :data="goodsList" tooltip-effect="dark" style="" width="100%" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55">
					</el-table-column>
					<el-table-column label="品牌" align="left">
						<template slot-scope="scope">{{ scope.row.brandName?scope.row.brandName:'-' }}</template>
					</el-table-column>
					<el-table-column label="商品名称" align="center">
						<template slot-scope="scope">{{ scope.row.goodsName?scope.row.goodsName:'-' }}</template>
					</el-table-column>
					<el-table-column label="OEM编码" align="center">
						<template slot-scope="scope">{{ scope.row.oem?scope.row.oem:'-' }}</template>
					</el-table-column>
					<el-table-column prop="exclusiveCode" label="横向件专属码" align="center">
						<template slot-scope="scope">{{ scope.row.transversePieceCode?scope.row.transversePieceCode:'-' }}</template>
					</el-table-column>
					<el-table-column prop="categoryParentName" label="品类" align="center" width="200">
					</el-table-column>
					<!-- <el-table-column prop="catId2" label="二级品类" align="center">
					</el-table-column> -->
					<el-table-column prop="code" label="商品编码" align="center">
					</el-table-column>
					<el-table-column prop="salePrice" label="价格" align="center">
					</el-table-column>
					<el-table-column label="商品状态" align="center">
						<template slot-scope="scope">{{ scope.row.status?'上架':'下架' }}</template>
					</el-table-column>
					<el-table-column prop="gmtCreate" label="创建时间" align="center" width="200">
					</el-table-column>
					<!-- <el-table-column prop="createUserId" label="创建人" align="center">
					</el-table-column> -->
					<el-table-column fixed="right" label="操作" align="center" >
						<template slot-scope="scope">
							<el-button @click="handleModelClick(scope.row)" type="text" size="small">适配车型</el-button>
							<el-button type="text" size="small" @click="editModelClick(scope.row)">编辑</el-button>
							<el-button type="text" size="small" style="color:red" v-if="scope.row.status" @click="updateStatusFn(scope.row,1)">下架</el-button>
							<el-button type="text" size="small" style="color:green" v-else @click="updateStatusFn(scope.row,2)">上架</el-button>
							<el-button type="text" size="small" style="color:red" @click="deleteClick(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>
		</div>
		<current-page :current-page="page" :page-size="pageSize" :page-total="pageTotal" @handleCurrentChange="handleCurrentChange">
		</current-page>
		<!-- <input  type="file" @change="uploadImg($event,'cover')" multiple="multiple" /> -->
		<input type="file" ref="logo" style="display:none;" @change="upload();" multiple="multiple" />
		<input type="file" ref="export" style="display:none;" @change="exportExcelFn();" multiple="multiple" />
		<div class="fil-box" v-if="export_url">
			<div class="dowdBox">
				<span class="dowdBox-title">导出数据完成</span>
				<a v-bind:href="export_url"  @click="hideXxUrl" download="product.xlsx">点击下载</a>
				<span class="close-box" @click="hideXxUrl">点击关闭</span>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		mapMutations,
		mapGetters
	} from 'vuex'
	import {
		getToken
	} from '@/utils/auth'
	// 成功常量 200
	import {
		SUCCESS_REQUEST_STATUS
	} from '@/utils/config.js'
	// 分页模块
	import currentPage from '@/components/current-page/current-page.vue'
	export default {
		data() {
			return {
				beginTime: null,			// 开始时间
				endTime: null,				// 结束时间
				page: 0,					// 当前页面
				offset: 0,					// 第几页开始
				downloadUrl: '',
				pageSize: 10,				// 每页显示多少条
				pageTotal: 0,				// 总条数
				brandName: '',				// 品牌名称
				fileType: 'cover',			// 类型
				goodsModelNumber: '',		// 商品车型编码
				firstCatId: '',				// 一级分类id
				secCatId: '',				// 二级分类id
				export_url: '',				// 导出数据url			
				firstCatList: [],			// 一级分类数组
				secCatList: [],				// 二级分类数组
				cateObject: null,			// 数据			
				filterNedTime: '',			// 过滤后的结束时间格式
				filterBeginTime: null,		// 过滤后的开始时间格式
				goodsList: [],				// 商品列表数据
				multipleSelection: [],		// 选择列表数据
				fullscreenLoading: false,	// 是否显示loadiing
				onlineStatus: null,			// 选择上下架状态
				onlineList:[				// 上下架数组
					{
						label:'上架',
						value: 1
					},
					{
						label:'下架',
						value: 0
					}
				],
				// 时间格式
				pickerOptions1: {
					shortcuts: [{
						text: '今天',
						onClick(picker) {
							picker.$emit('pick', new Date());
						}
					}, {
						text: '昨天',
						onClick(picker) {
							const date = new Date();
							date.setTime(date.getTime() - 3600 * 1000 * 24);
							picker.$emit('pick', date);
						}
					}, {
						text: '一周前',
						onClick(picker) {
							const date = new Date();
							date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
							picker.$emit('pick', date);
						}
					}]
				},
			}
		},
		created() {
			// 初始化数据
			this._initData()
			this._getCategory()
		},
		methods: {
			importTemplateFn() {
				this.$get({
					url: 'goods/import/template/',
					callback: res => {
						console.log(res)
						if(res.status == 200) {
							this.downloadUrl = res.data
						}
					}
				})
			},
			selectOnlineFn(){
				this._initData()
			},
			hideXxUrl(){
				this.export_url = ''
			},
			// 批量导入
			batchExportFn() {
				this.$refs.export.click();
			},
			// 导入excel
			exportExcelFn(e) {
				let files = this.$refs.export.files[0]
				if (files.name.indexOf('xlsx') != -1 || files.name.indexOf('xls') != -1) {
					this.fullscreenLoading = true;
					var formData = new FormData()
					formData.append('file', files)
					formData.append('merchantId', window.sessionStorage.getItem('merchantId'))
					this.$post({
						url: `goods/import/${window.sessionStorage.getItem('merchantId')}`,
						data: {
							file: formData
						},
						excel: true,
						callback: res => {
							console.log(res)
							if(res.status === 200) {
								this.$message({
									type: 'success',
									message: '导入成功'
								})
								this.$refs.export.value = ''
								this._initData()
							}else{
								this.$refs.export.value = ''
							}
							this.fullscreenLoading = false
						}
					})
				} else {
					this.$message('请选择正确的文件格式')
				}
			},
			// 清空图片
			closeImgAll() {
				let attr = []
				if (!this.multipleSelection.length) {
					this.$message({
						type: 'error',
						message: '请选择要清空的商品'
					})
					return
				}
				this.multipleSelection.forEach((item) => {
					attr.push(item.id)
				})
				this.$confirm("提示", "确定清空图片？", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					this.$delete({
						url: 'goods/picture/',
						data:attr ,
						special: true,
						callback: res => {
							console.log(res)
							if(res.status === SUCCESS_REQUEST_STATUS) {
								this.$message({
									type: 'success',
									message: '清空成功'
								})
							}else {
								this.$message({
									type: 'error',
									message: res.msg
								})
							}
						}
					})
				})
			},
			// 新建商品
			newProductFn() {
				let attrObj = {
					goodId: '',
					gcId: '',
					goBackFlag: false,
					firstCartId: '',
					secondCartId: '',
					queryAttrList: null
				}
				this.setStepCache(attrObj)
				this.$emit('newProductFn')
			},
			// 编辑车型
			editModelClick(item) {
				let attrObj = Object.assign({}, this.getStepCache,{secondCartId: item.secCatId, goodId: item.goodsId,firstCartId:item.firCatId,queryAttrList:null,goBackFlag: false})
				this.setStepCache(attrObj),
				this.$emit('editModelClick', item)
			},
			// 点击适配车型
			async handleModelClick(item) {
				let attr = {
					goodId: item.goodsId,
					firstCartId: item.firCatId,
					secondCartId: item.secCatId,
					goBackFlag: false
				}
				let list = await this._getQueryAttr(item).then(res => {
					if(res instanceof Array) {
						return res
					}else {
						return []
					}
				})
				attr.queryAttrList = list 
				this.setStepCache(attr)
				this.$emit('handleModelClick', item)
			},
			_getQueryAttr(item) {
				return new Promise((reslove, reject) => {
					this.$ajax({
						api: 'merchant/goods/queryAttr',
						params: {
							token: getToken(),
							goodsId: item.goodsId,
							merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') :
								'',
						}
					}).then(res => {
						if (res.status === SUCCESS_REQUEST_STATUS) {
							 reslove(res.data)
						}else{
							reject(res.data.message)
						}
					}).catch(err => {
						reject(err.message)
					})
				 })
			},
			uploadImg() {
				this.$refs.logo.click();
			},
			upload(e) {
				let fileLength = 0 
				if (!this.$refs.logo.files[0]) {
					return;
				}
				this.fullscreenLoading = true
				if (Object.values(this.$refs.logo.files).length > 0 && Object.values(this.$refs.logo.files).length <= 100) {
					Object.values(this.$refs.logo.files).forEach((item, index) => {
						let formData = new FormData() 
						formData.append('files', this.$refs.logo.files[index])
						formData.append('merchantId', window.sessionStorage.getItem('merchantId'))
						this.$post({
							excel: true,
							url: `goods/picture/${window.sessionStorage.getItem('merchantId')}`,
							data: {
								file: formData  
							},
							callback: res => {
								console.log(res)
								if(res.status === 200) {
									fileLength++
									if (fileLength == this.$refs.logo.files.length) {
										this.$message({
											message: '上传成功',
											type: 'success'
										});
										this.$refs.logo.value = ''
										this.fullscreenLoading = false
									}
								}else {
									this.$message({
										type: 'error',
										message: err.message
									})
									this.$refs.logo.value = ''
									this.fullscreenLoading = false
								}
							}
						})
					})
				} else {
					_this.$message("上传图片不能多于100张");
				}
			},
			screenFn(num) {
				this.page = 0
				if (num == 2) {
					this.offset = 0
					this.page = 0
					this.beginTime = this.endTime = this.brandName = this.goodsModelNumber = this.firstCatId = this.secCatId = this.filterNedTime =
						this.filterBeginTime = this.onlineStatus = ''
				}
				this._initData()
			},
			/**
			 * @desc 处理上下架
			 * @param type 是否批量下架
			 */
			updateStatusAllFn(type) {
				let attr = []
				if (!this.multipleSelection.length) {
					this.$message({
						type: 'error',
						message: '请先勾选需要下架的商品'
					})
					return
				}
				this.multipleSelection.forEach((item) => {
					attr.push(item.id)
				})
				this.$put({
					url: `goods/${type ? 'batchPutOnShelves' : 'batchPutOffShelves'}/`,
					data: attr,
					callback: res => {
						console.log(res)
						if(res.status === SUCCESS_REQUEST_STATUS) {
							this.$message({
								type: 'success',
								message: `${!type? '下架' : '上架'}商品成功`
							})
							this._initData()
						} else {
							this.$message({
								type: 'error',
								message: err.msg
							})
						}
					}
				})
			},
			/**
			* @desc 上下架商品
			* @param item 当前选中的商品
			* @param num 1 下架 2 上架
			*/
			updateStatusFn(item, num) {
				this.$confirm("提示", `确定${num==1?'下架':'上架'}此商品？`, {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					this.$put({
						url: `goods/${num == 1 ? 'putOffShelves' : 'putOnShelves'}/${item.id}`,
						callback: res => {
							console.log(res)
							if(res.status === SUCCESS_REQUEST_STATUS) {
								this.$message({
									type: 'success',
									message: `${num==1?'下架':'上架'}商品成功`
								})
								this._initData()
							}else {
								this.$message({
									type: 'error',
									message: err.msg
								})
							}
						}
					})
				})

			},
			/**
			 * @desc 获取一级分类
			 */
			_getCategory() {
				this.$get({
					url: `goods/category/${window.sessionStorage.getItem('merchantId')}`,
					callback: res => {
						console.log(res)
						if (res.status === SUCCESS_REQUEST_STATUS) {
							if (res.data && res.data.length > 0) {
								res.data.forEach((item) => {
									let obj = {
										value: item.id,
										label: item.categoryName
									}
									this.firstCatList.push(obj)
								})
								this.cateObject = res.data
							}
						}else {
							this.$message({
								type: 'error',
								message: err.msg
							})
						}
					}
				})
			},
			/**
			 * @desc 批量删除商品
			 */
			deleteAllClick() {
				let attr = []
				if (!this.multipleSelection.length) {
					this.$message({
						type: 'error',
						message: '请选择商品'
					})
					return
				}
				this.multipleSelection.forEach((item) => {
					attr.push(item.id)
				})
				this.$delete({
					url: 'goods/',
					special: true,
					data: attr,
					callback: res => {
						console.log(res)
						if(res.status === SUCCESS_REQUEST_STATUS) {
							this.$message({
								type: 'success',
								message: '删除成功'
							})
							this.page = 0
							this._initData()
						}else {
							this.$message({
								type: 'error',
								message: err.msg
							})
						}
					}
				})
			},
			// 删除商品
			deleteClick(item) {
				this.$confirm("提示", "确认删除此商品吗？", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					this.$delete({
						url: `goods/${item.id}`,
						callback: res => {
							if(res.status === SUCCESS_REQUEST_STATUS) {
								this.$message({
									type: 'success',
									message: '删除成功'
								})
								this._initData()
							}
						}
					})
				})
			},
			handleSelectionChange(val) {
				this.multipleSelection = val
			},
			handleCurrentChange(page) {
				this.offset = ((page+1)-1) * this.pageSize
				this._initData()
			},
			_initData() {
				console.log(this.beginTime)
				this.fullscreenLoading = true
				this.$get({
					url: 'goods/',
					data: {
						offset: this.offset,
						size: this.pageSize,
						code: this.goodsModelNumber ? this.goodsModelNumber : null,
						startTime: this.filterBeginTime ? this.filterBeginTime : null,
						endTime: this.filterNedTime ? this.filterNedTime : null,
						brandName: this.brandName ? this.brandName : null,
						categoryParentId: this.firstCatId ? this.firstCatId : null,
						categoryId: this.secCatId ? this.secCatId : null , 
						status: this.onlineStatus != null ? this.onlineStatus : null,
						merchantId: window.sessionStorage.getItem('merchantId')
					},
					callback: res => {
						console.log(res)
						if(res.status === SUCCESS_REQUEST_STATUS) {
							this.goodsList = res.data.list
							this.pageTotal = res.data.total
							this.page = (this.pageTotal-1) / 10 + 1
						}else {
							this.$message({
								type: 'error',
								message: res.msg
							})
						}
						this.fullscreenLoading = false
					}
				})
			},
			/**
			 *  格式化时间
			 *	@param {String}  unixTime 时间戳
			 * 	@param {Boolean}  isFull 是否到毫秒级
			 *  注 可以做成公用函数 优化
			 * */
			TransformationTime(time, isFull) {
				var ymdhis = ""
				ymdhis += time.getFullYear() + "-"
				ymdhis += (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) + "-" : (time.getMonth() + 1) + "-"
				ymdhis += time.getDate() < 10 ? '0' + time.getDate() : time.getDate()
				if (isFull === true) {
					ymdhis += " " + time.getHours() < 10 ? " " + '0' + time.getHours() + ":" : " " + time.getHours() + ":"
					ymdhis += time.getMinutes() < 10 ? '0' + time.getMinutes() + ":" : time.getMinutes() + ":"
					ymdhis += time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
				}
				return ymdhis
			},
			// 获取前一周时间
			getOneWeekDate(num) {
				let before = ''
				let target = new Date()
				let nowdate = new Date()
				switch (num) {
					case 1:
						before = new Date(nowdate - (7 * 24 * 3600 * 1000))
						break;
					case 2:
						nowdate.setMonth(nowdate.getMonth() - 1);
						before = nowdate
						nowdate = target
						break;
				}
				this.filterBeginTime = this.beginTime =
					`${before.getFullYear()}-${(before.getMonth() +1)}-${before.getDate()} 00:00:00`
				this.filterNedTime = this.endTime =
					`${nowdate.getFullYear()}-${(nowdate.getMonth() +1)}-${nowdate.getDate()} 00:00:00`

			},
			handleQuery(param) {
				return param != null ? param : ''
			},
			...mapMutations({
				setStepCache: 'SET_STEP_CACHE',
			})
		},
		watch: {
			firstCatId(val, oldVal) {
				if (val && oldVal != val) {
					for (let k in this.cateObject) {
						console.log(this.cateObject[k])
						if (this.cateObject[k].id == val) {
							this.secCatList = []
							this.cateObject[k].children.forEach((item) => {
								let chlObj = {
									value: item.id,
									label: item.categoryName
								}
								this.secCatList.push(chlObj)
							})
						}
					}
				}
			},
			beginTime: function (val) {
				if (val) {
					val = typeof val == 'string' ? new Date(val) : val
					this.filterBeginTime = this.TransformationTime(val, true)
					console.log(this.filterBeginTime)
					return
				}
				this.filterBeginTime = ''
			},
			endTime: function (val) {
				if (val) {
					val = typeof val == 'string' ? new Date(val) : val
					this.filterNedTime = this.TransformationTime(val, true)
					return
				}
				this.filterNedTime = ''
			}
		},
		components: {
			currentPage
		},
		computed: {
			handle_goods_url() {
				// 开发场写死地址 后面 config 文件 引进地址
				let str = 'http://118.31.19.251:9001/goods/export/?'
				let merId = window.sessionStorage.getItem('merchantId')
				return `${str}offset=${this.offset}&size=${this.pageSize}&code=${this.goodsModelNumber}&merchantId=${merId}&startTime=${this.handleQuery(this.filterBeginTime)}&endTime=${this.handleQuery(this.filterNedTime)}&brandName=${this.brandName}&categoryParentId=${this.firstCatId}&categoryId=${this.secCatId}&status=${this.handleQuery(this.onlineStatus)}`
			},
			...mapGetters([
				'getStepCache'
			])
		}
	}
</script>
